﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.VisualBasic;
using UsedBookTradeSystem.DBContext;
using UsedBookTradeSystem.Models.Dtos.InputDtos;

namespace UsedBookTradeSystem.Controllers.BackendControllers
{
    public class AdminController : Controller
    {
        private readonly SystemDbContext _ctx;

        public AdminController(SystemDbContext dbContext)
        {
            _ctx = dbContext;
        }

        [Authorize(Roles = "Admin")]
        public IActionResult MyInfo()
        {
            if (string.IsNullOrWhiteSpace(User.Identity.Name)) 
            {
                TempData["LoginFail"] = "请重新登陆！";
                return View(nameof(Index),"Home");
            }
            var userInfo = _ctx.Users.First(x => x.UserName == User.Identity.Name);
            ViewBag.UserInfo = userInfo;
            return View();
        }
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> UpdateMyInfo(UpdateUserInput updateUserInput) 
        {
            if (string.IsNullOrWhiteSpace(updateUserInput.UserName) ||
                string.IsNullOrWhiteSpace(updateUserInput.PassWord) ||
                string.IsNullOrWhiteSpace(updateUserInput.ConfirmPassword) ||
                string.IsNullOrWhiteSpace(updateUserInput.Tel) ||
                updateUserInput.PassWord != updateUserInput.ConfirmPassword ||
                updateUserInput.Tel.Length != 11)
            {
                TempData["OperateResult"] = "输入不合法！";
                return View(nameof(Index));
            }
            if (!UInt64.TryParse(updateUserInput.Tel, out UInt64 n))
            {
                TempData["OperateResult"] = "请输入正确的手机号码！";
                return RedirectToAction(nameof(Index));
            }
            //若两次密码不一致则提示不同
            if (updateUserInput.PassWord!=updateUserInput.ConfirmPassword) 
            {
                TempData["OperateResult"] = "两次密码不同";
                return RedirectToAction(nameof(MyInfo));
            }
            //根据回传ID获取对象
            var user = await _ctx.Users.FirstAsync(x=>x.Id==updateUserInput.Id);
            //若为非空或非空格则修改密码
            if (!string.IsNullOrWhiteSpace(updateUserInput.PassWord))
                user.PassWord = updateUserInput.PassWord;
            user.Gender = updateUserInput.Gender;
            user.UpdatedTime = DateTime.Now;
            _ctx.Users.Update(user);
            await _ctx.SaveChangesAsync();
            TempData["OperateResult"] = "修改成功，请重新登录";
            return RedirectToAction(nameof(Index),"Home");
        }
    }
}
